package cn.demo.thread;

/**
 * 生产者和消费者
 *
 * @author duxiaod
 * @date 2021/07/24 20:15
 **/
public class PrividerAndConsumer {
    private static volatile boolean flag = false;

    public static void main(String[] args) {
        new Thread(new Privider()).start();
        new Thread(new Consumer()).start();
    }

    // 生产者
    public static class Privider implements Runnable{

        @Override
        public void run() {
            while (true){
                synchronized (PrividerAndConsumer.class){
                    if(!flag){
                        System.out.println("生产者开始生产");
                        flag = true;
                        try {
                            PrividerAndConsumer.class.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    // 消费者
    public static class Consumer implements Runnable{

        @Override
        public void run() {
            while (true){
                synchronized (PrividerAndConsumer.class){
                    if(flag){
                        System.out.println("消费者开始消费");
                        flag = false;
                        PrividerAndConsumer.class.notify();
                    }
                }
            }
        }
    }
}
